<template>
  <div class="relative flex-1 max-w-2xl mx-2 sm:mx-4">
    <!-- 搜索输入框 -->
    <div class="relative">
      <input
        ref="searchInput"
        v-model="searchQuery"
        type="text"
        placeholder="搜索电影、演员、导演..."
        class="w-full px-3 sm:px-4 py-2 pl-10 sm:pl-12 pr-16 sm:pr-20 bg-background-800/80 backdrop-blur-sm border border-background-600 rounded-full text-text-primary placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-normal text-sm sm:text-base"
        @focus="showSuggestions = true"
        @blur="handleBlur"
        @keydown.enter="handleSearch"
        @input="handleInput"
        style="pointer-events: auto;"
      />
      
      <!-- 搜索图标 -->
      <div class="absolute left-3 sm:left-4 top-1/2 transform -translate-y-1/2">
        <svg class="w-4 sm:w-5 h-4 sm:h-5 text-text-muted" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
          <circle cx="11" cy="11" r="8"/>
          <path d="M21 21l-4.35-4.35"/>
        </svg>
      </div>
      
      <!-- 搜索按钮 -->
      <button
        @click="handleSearch"
        type="button"
        class="absolute right-1 sm:right-2 top-1/2 transform -translate-y-1/2 px-2 sm:px-4 py-1 h-7 sm:h-8 min-w-[48px] sm:min-w-[60px] flex items-center justify-center cursor-pointer z-10 bg-background-600 hover:bg-background-500 text-text-primary rounded-full transition-colors duration-normal font-medium text-xs sm:text-sm border border-background-500 focus:outline-none focus:ring-2 focus:ring-background-400 focus:ring-offset-2 focus:ring-offset-background-800"
      >
        <span class="hidden sm:inline">搜索</span>
        <span class="sm:hidden">搜</span>
      </button>
    </div>

    <!-- 搜索建议下拉框 -->
    <div
      v-if="showSuggestions && suggestions.length > 0"
      class="absolute top-full left-0 right-0 mt-2 bg-background-800 border border-background-600 rounded-lg shadow-lg z-50 max-h-80 overflow-y-auto animate-slide-down"
      :class="{
        'max-w-[calc(100vw-2rem)]': true,
        'left-0 right-auto': true
      }"
    >
      <div class="py-2">
        <div
          v-for="(suggestion, index) in suggestions"
          :key="index"
          @click="selectSuggestion(suggestion)"
          class="px-3 sm:px-4 py-2 sm:py-3 hover:bg-background-700 cursor-pointer transition-all duration-normal flex items-center gap-2 sm:gap-3"
        >
          <!-- 搜索图标 -->
          <svg class="w-4 h-4 text-text-muted flex-shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
            <circle cx="11" cy="11" r="8"/>
            <path d="M21 21l-4.35-4.35"/>
          </svg>
          
          <!-- 建议内容 -->
          <div class="flex-1 min-w-0">
            <div class="text-text-primary text-sm truncate">{{ suggestion.text }}</div>
            <div v-if="suggestion.type" class="text-text-muted text-xs mt-1">
              {{ getTypeLabel(suggestion.type) }}
            </div>
          </div>
          
          <!-- 类型标签 -->
          <span
            v-if="suggestion.type"
            class="px-2 py-1 text-xs rounded-full flex-shrink-0"
            :class="getTypeClass(suggestion.type)"
          >
            {{ getTypeShortLabel(suggestion.type) }}
          </span>
        </div>
      </div>
    </div>

    <!-- 最近搜索 -->
    <div
      v-if="showSuggestions && suggestions.length === 0 && recentSearches.length > 0"
      class="absolute top-full left-0 right-0 mt-2 bg-background-800 border border-background-600 rounded-lg shadow-lg z-50 animate-slide-down"
      :class="{
        'max-w-[calc(100vw-2rem)]': true,
        'left-0 right-auto': true
      }"
    >
      <div class="py-2">
        <div class="px-3 sm:px-4 py-2 text-text-muted text-sm font-medium border-b border-background-700">
          最近搜索
        </div>
        <div
          v-for="(search, index) in recentSearches"
          :key="index"
          @click="selectRecentSearch(search)"
          class="px-3 sm:px-4 py-2 sm:py-3 hover:bg-background-700 cursor-pointer transition-all duration-normal flex items-center justify-between"
        >
          <div class="flex items-center gap-2 sm:gap-3 min-w-0 flex-1">
            <svg class="w-4 h-4 text-text-muted flex-shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
              <path d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
            <span class="text-text-primary text-sm truncate">{{ search }}</span>
          </div>
          <UiButton
            @click.stop="removeRecentSearch(index)"
            variant="ghost"
            size="sm"
            class="text-text-muted hover:text-text-primary p-0 h-auto flex-shrink-0"
          >
            <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>
            </svg>
          </UiButton>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useSearch } from '../../composables/useSearch'

const router = useRouter()
const { 
  suggestions, 
  recentSearches, 
  loadRecentSearches, 
  removeRecentSearch, 
  generateSuggestions 
} = useSearch()

// 响应式数据
const searchQuery = ref('')
const showSuggestions = ref(false)
const searchInput = ref<HTMLInputElement>()

// 处理输入
const handleInput = () => {
  if (searchQuery.value.trim()) {
    generateSuggestions(searchQuery.value)
  } else {
    suggestions.value = []
  }
}

// 选择建议
const selectSuggestion = (suggestion: any) => {
  searchQuery.value = suggestion.text
  handleSearch()
}

// 选择最近搜索
const selectRecentSearch = (search: string) => {
  searchQuery.value = search
  handleSearch()
}

// 处理搜索
const handleSearch = () => {
  const query = searchQuery.value.trim()
  if (!query) return
  
  showSuggestions.value = false
  
  // 跳转到搜索结果页面
  router.push({
    name: 'SearchResults',
    query: { q: query }
  })
}

// 处理失焦
const handleBlur = () => {
  setTimeout(() => {
    showSuggestions.value = false
  }, 200)
}

// 获取类型标签
const getTypeLabel = (type: string) => {
  const labels = {
    movie: '电影',
    actor: '演员',
    director: '导演',
    genre: '类型'
  }
  return labels[type as keyof typeof labels] || ''
}

// 获取类型短标签
const getTypeShortLabel = (type: string) => {
  const labels = {
    movie: '电影',
    actor: '演员',
    director: '导演',
    genre: '类型'
  }
  return labels[type as keyof typeof labels] || ''
}

// 获取类型样式类
const getTypeClass = (type: string) => {
  const classes = {
    movie: 'bg-primary-600/20 text-primary-300 border-primary-600/30',
    actor: 'bg-success/20 text-success border-success/30',
    director: 'bg-ai-generated/20 text-ai-generated border-ai-generated/30',
    genre: 'bg-warning/20 text-warning border-warning/30'
  }
  return classes[type as keyof typeof classes] || 'bg-background-600/20 text-text-muted border-background-600/30'
}

// 点击外部关闭建议
const handleClickOutside = (event: Event) => {
  const target = event.target as HTMLElement
  if (!target.closest('.relative')) {
    showSuggestions.value = false
  }
}

onMounted(() => {
  loadRecentSearches()
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script> 